package com.ruiysoft.controller.statement;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruiysoft.controller.statement.vo.StatementAuditConditionVo;
import com.ruiysoft.controller.statement.vo.StatementAuditListVo;
import com.ruiysoft.controller.sys.api.InnerMicroprogramApi;
import com.ruiysoft.controller.sys.api.SysUserApi;
import com.ruiysoft.controller.sys.res.UserShopResponse;
import com.ruiysoft.entity.statement.StatementShop;
import com.ruiysoft.entity.statement.StatementShopDetail;
import com.ruiysoft.entity.sys.SysUser;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.service.statement.IStatementShopDetailService;
import com.ruiysoft.service.statement.IStatementShopService;
import com.ruiysoft.service.statement.consts.StatementAuditStatus;
import com.ruiysoft.util.NumberUtils;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-01-13T17:59:57.541+08:00")

@RestController
public class OprShopStatementApiController implements OprShopStatementApi {

    private static final Logger log = LoggerFactory.getLogger(OprShopStatementApiController.class);

    private final IStatementShopService statementShopService;

    private final IStatementShopDetailService statementShopDetailService;

    private final SysUserApi sysUserApi;

    private final InnerMicroprogramApi innerMicroprogramApi;
    @org.springframework.beans.factory.annotation.Autowired
    public OprShopStatementApiController(IStatementShopService statementShopService, IStatementShopDetailService statementShopDetailService, SysUserApi sysUserApi, InnerMicroprogramApi innerMicroprogramApi) {
        this.statementShopService = statementShopService;
        this.statementShopDetailService = statementShopDetailService;
        this.sysUserApi = sysUserApi;
        this.innerMicroprogramApi = innerMicroprogramApi;
    }

    @Override
    public Result<PageInfo<StatementAuditListVo>> oprShopStatementAuditListGet(@NotNull @ApiParam(value = "分页开始页", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页显示多少条数据", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, @ApiParam(value = "审核状态（0，所有，1，未审核，2，审核通过，3，不通过）") @Valid @RequestParam(value = "auditType", required = true) Integer auditType, @ApiParam(value = "店铺id") @Valid @RequestParam(value = "shopId", required = false) Long shopId) {
        QueryWrapper<StatementShopDetail> entityWrapper = new QueryWrapper<StatementShopDetail>();

        entityWrapper.select("statement_id statementId,MAX(audit_status) auditStatus,MAX(work_date) workDate")
                .eq(shopId!=null,"shop_id",shopId)
                .groupBy("statement_id").orderBy(false,false,"workDate");
        if(!Integer.valueOf(0).equals(auditType)) {
            //auditType == 0，则不增加此过滤，表示查询所有
            entityWrapper.having("MAX(audit_status) = {0}", auditType);
        }

        IPage<Map<String, Object>> detailPage = statementShopDetailService.pageMaps(new Page<>(pageStart,pageSize),entityWrapper);

        List<StatementAuditListVo> list = detailPage.getRecords().stream().filter(Objects::nonNull)
                .map(map->new StatementAuditListVo().id((Long)map.get("statementId")).auditType((Integer)map.get("auditStatus")).date(((Date)map.get("workDate")).getTime()))
                .collect(Collectors.toList());
        if(!list.isEmpty()){
            Set<Long> ids = list.stream().map(vo->vo.getId()).collect(Collectors.toSet());
            List<StatementShop> statementShops = (List<StatementShop>) statementShopService.listByIds(ids);
            Map<Long,StatementShop> map = statementShops.stream().collect(Collectors.toMap(statementShop->statementShop.getId(),statementShop->statementShop));
            Set<Long> shopIds = statementShops.stream().map(statementShop->statementShop.getShopId()).collect(Collectors.toSet());
            List<UserShopResponse> userShopResponses = getUserShopResponses(shopIds);
            Map<Long,UserShopResponse> userShopResponseMap = userShopResponses.stream().collect(Collectors.toMap(userShopResponse->userShopResponse.getId(),userShopResponse->userShopResponse));
            list.stream().forEach(vo->{
                StatementShop ss = map.get(vo.getId());
                vo.money(NumberUtils.changeF2Y2(ss.getMoney().toString()));
                UserShopResponse userShopResponse = userShopResponseMap.get(ss.getShopId());
                if(userShopResponse!=null){
                    vo.personalName(userShopResponse.getRealName()).personalPhone(userShopResponse.getMobile()).shopName(userShopResponse.getShopName());
                }
            });

        }

        return ResultGenerator.genSuccessResult(new PageInfo<StatementAuditListVo>(list, (Page) detailPage));
    }

    private List<UserShopResponse> getUserShopResponses(Set<Long> shopIds) {
        if(shopIds==null&&shopIds.isEmpty()){
            return new ArrayList<>();
        }
        Result<List<UserShopResponse>> result = innerMicroprogramApi.getShopInfos(shopIds.toArray(new Long[shopIds.size()]));
        if(result.isSuccess()||result.getData()!=null){

            return result.getData();
        }else{
            return new ArrayList<>();
        }
    }

    private SysUser getSysUserByShopId(Long shopId) {
        Result<SysUser> result = sysUserApi.getShopkeeper(shopId);
        if(result.isSuccess()||result.getData()!=null){
//            throw new Exception("获取店铺所属用户错误");

            return result.getData();
        }else{
            return new SysUser();
        }
    }

    @Override
    public Result<Void> oprShopStatementAuditPut(@ApiParam(value = ""  )  @Valid @RequestBody StatementAuditConditionVo body) {
        List<StatementShop> list = (List<StatementShop>) statementShopService.listByIds(body.getIds());
        list.forEach(statementShop -> {
            SysUser user = getSysUserByShopId(statementShop.getShopId());
            statementShopService.expenditure(statementShop,user.getPersonnelId(),StatementAuditStatus.getEnum(body.getType()),body.getInfo());
        });
        return ResultGenerator.genSuccessResult();
    }

}
